package com.apes.framework.util.bean.compiler;

import com.apes.framework.util.ClassPathScanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 功能：
 *
 * @author xul
 * @create 2018-11-17 11:06
 */
@Slf4j
public class DynamicEngine {

    private static DynamicEngine instance = new DynamicEngine();
    private final CharSequenceCompiler compiler;
    private final ApesClassLoaderImpl loader;
    private final Map<String, Class> managedClasses = new HashMap<>();

    public static DynamicEngine getInstance() {
        return instance;
    }

    private DynamicEngine() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader instanceof ApesClassLoaderImpl) {
            loader = (ApesClassLoaderImpl) classLoader;
        } else {
            loader = new ApesClassLoaderImpl(classLoader);
        }
        List<String> options = new ArrayList<>();
        options.addAll(Arrays.asList("-target", "1.8"));
        String classPath = ClassPathScanUtil.getClassPath();
        if (!StringUtils.isEmpty(classPath)) {
            options.addAll(Arrays.asList("-classpath", classPath));
        }
        compiler = new CharSequenceCompiler(loader, options);
    }

    public Map<String, Class> compile(final Map<String, CharSequence> classes) throws CharSequenceCompilerException, ClassCastException {
        if (classes == null || classes.isEmpty()) return null;
        return compiler.compile(classes, null);
    }

    public ApesClassLoaderImpl getLoader() {
        return loader;
    }

    public Map<String, Class> getManagedClasses() {
        return managedClasses;
    }

    public void addClass(String name, Class clazz){
        managedClasses.put(name, clazz);
    }
}
